from dash import Dash, html, dcc, Input, Output
import plotly.graph_objects as go

# 初始化 Dash 应用
app = Dash(__name__)

# 初始化数据
data = {
    'x': [],
    'y': [],
    'z': []
}

# 定义布局
app.layout = html.Div([
    html.H1("三维散点图示例", style={'textAlign': 'center'}),
    html.Div([
        html.Div([
            html.Label("X 轴:"),
            dcc.Input(id='x-input', type='number', placeholder='输入 X 值', style={'margin-right': '10px'})
        ], style={'display': 'inline-block', 'margin-right': '20px'}),
        html.Div([
            html.Label("Y 轴:"),
            dcc.Input(id='y-input', type='number', placeholder='输入 Y 值', style={'margin-right': '10px'})
        ], style={'display': 'inline-block', 'margin-right': '20px'}),
        html.Div([
            html.Label("Z 轴:"),
            dcc.Input(id='z-input', type='number', placeholder='输入 Z 值', style={'margin-right': '10px'})
        ], style={'display': 'inline-block', 'margin-right': '20px'}),
        html.Button('添加点', id='add-point-button', style={'display': 'inline-block'})
    ], style={'textAlign': 'center', 'margin-bottom': '20px'}),
    dcc.Graph(id='3d-scatter-plot', style={'height': '600px'})
])

# 回调函数：处理按钮点击事件并更新图表
@app.callback(
    Output('3d-scatter-plot', 'figure'),
    Input('add-point-button', 'n_clicks'),
    Input('x-input', 'value'),
    Input('y-input', 'value'),
    Input('z-input', 'value')
)
def update_graph(n_clicks, x, y, z):
    if n_clicks is None:
        # 初始状态，返回空图表
        return {
            'data': [],
            'layout': {
                'title': '三维散点图',
                'scene': {
                    'xaxis': {'title': 'X 轴'},
                    'yaxis': {'title': 'Y 轴'},
                    'zaxis': {'title': 'Z 轴'}
                }
            }
        }

    # 检查输入值是否有效
    if x is None or y is None or z is None:
        return {
            'data': [],
            'layout': {
                'title': '三维散点图',
                'scene': {
                    'xaxis': {'title': 'X 轴'},
                    'yaxis': {'title': 'Y 轴'},
                    'zaxis': {'title': 'Z 轴'}
                }
            }
        }

    # 添加新点到数据中
    data['x'].append(x)
    data['y'].append(y)
    data['z'].append(z)

    # 创建三维散点图
    fig = go.Figure(data=[
        go.Scatter3d(
            x=data['x'],
            y=data['y'],
            z=data['z'],
            mode='markers',
            marker=dict(size=5))
    ])

    # 更新布局
    fig.update_layout(
        title='三维散点图',
        scene=dict(
            xaxis=dict(title='X 轴'),
            yaxis=dict(title='Y 轴'),
            zaxis=dict(title='Z 轴')
        )
    )

    return fig

# 运行应用
if __name__ == '__main__':
    app.run_server(debug=True)